import rq from 'request-promise'
// import _ from 'lodash'
import iconv from 'iconv-lite'
import { writeFileSync } from 'fs'
import { resolve } from 'path'
const r = path => resolve(__dirname, path)

let cityPath = r('../../json/city.json')
let cites = require(cityPath)
var isclearTimer = false
const sign = 'c0159e56b92b0f7e191b2228d917afc9'
let cityIdx = 0
let error = 0
let citys = []

const getApi = async () => {
  if (cites.length === cityIdx) {
    isclearTimer = true
    writeFileSync(cityPath, JSON.stringify(citys, null, 2), 'utf-8')
  }
  let city = cites[cityIdx].name
  console.log(city)
  var url = `http://cp-tools.cn/categroy/crumbs`
  console.log(url)
	const options = {
    url: url,
    json: true,
    qs: {
      city,
      sign
    }
	}
  var res = await rq(options)
  if (res.areas.length !== 0)  {
    cites[cityIdx].areas = res.areas

    citys.push(cites[cityIdx])
    
    cityIdx ++
    console.log(citys)
  } else if (error >= 2) {
    error = 0
    cityIdx ++
  } else {
    error ++
  }
}


const timer = setInterval(function() {
	getApi()
},3000)

const clearTime = setInterval(function() {
	if (isclearTimer) {
		clearInterval(timer)
	}
},1000)